﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Bzzb.Model;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;

namespace Bzzb.Controllers
{
    public class RolePermissionController : BaseController
    {
        private readonly ILogger<RolePermissionController> _logger;
        public RolePermissionController(ILogger<RolePermissionController> logger, IFreeSql fsql) : base(fsql)
        {
            this._logger = logger;
        }

        [HttpPost]
        public async Task<IDictionary<string, Object>> Index([FromForm] long rid)
        {
            List<long> pmids = await _fsql.Select<RolePermission>().Where(rp => rp.Rid == rid).ToListAsync(rp => rp.Pmid);
            _logger.LogInformation(_fsql.Select<RolePermission>().Where(rp => rp.Rid == rid).ToSql(rp => rp.Pmid));
            return RenderJson(data: pmids);
        }

        [HttpPost]
        public async Task<IDictionary<string, Object>> Save([FromForm] long rid, [FromForm] long[] pmids, [FromForm] string pmidsData)
        {
            int affrows = -1;
            _fsql.Transaction(() => {
                // 添加前端需要的字段
                _fsql.Update<Role>(rid).Set(r => r.PmidsData, pmidsData).ExecuteAffrows();
                // 先清空之前所有角色权限
                affrows = _fsql.Delete<RolePermission>().Where(rp => rp.Rid == rid).ExecuteAffrows();

                List<RolePermission> rolePermissions = new List<RolePermission>();
                foreach (long pmid in pmids)
                {
                    rolePermissions.Add(new RolePermission { Rid = rid, Pmid = pmid });
                }
                affrows = _fsql.Insert(rolePermissions).ExecuteAffrows();
            });
            
            return RenderJson(data: affrows);
        }

        [HttpPost]
        public async Task<IDictionary<string, Object>> Delete([FromForm] long rid, [FromForm] long pmid) {
            int affrows = await _fsql.Delete<RolePermission>().Where(rp => rp.Rid == rid && rp.Pmid == pmid).ExecuteAffrowsAsync();
            return RenderJson(data: affrows);
        }
    }
}
